<?php

if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once APPPATH . 'libraries/kosolr_bootstrap.php';

/**
 * Description of MY_Controller.php
 *
 * @author luubk
 * @since Feb 16, 2012 - 3:15:26 PM
 */
class MY_Controller extends CI_Controller
{
    protected $data = array();
    protected $theme = 'default';
    protected $template = 'template';
    protected $left_items = array();
    protected $right_items = array();
    protected $_plugins = array();
    protected $_css = array();
    protected $_js = array();
    protected $_ignore = array();
    protected $owner_id = FALSE;
    protected $solr_server_configuration = array(
        'server' => '192.168.33.253',
        'port' => 8983,
        'app_path' => '/solr',
        'core' => 'kgv'
    );

    protected $kosolr_server_instance = NULL;
    protected $media_server;

    function __construct()
    {       
        parent::__construct();
        // load acx configuration
		$this->config->load('acx');

		$this->media_server = $this->config->item('media_server');

        $this->config->set_item('language', 'vietnamese');
        $this->load->driver('cache', array('adapter' => 'file', 'backup' => 'file'));

        $this->load->helper('number');
        
        if ($this->session->userdata('loggedin', ''))
                $this->owner_id = $this->session->userdata('owner_id', '');

        $this->load->helper('util');
        $this->load->helper('cookie');
        $this->load->library('asset_files');
        $this->set_var('assets', base_url() . 'assets/template/default/');
        $this->data['_plugins'] = & $this->_plugins;
        $this->data['_css'] = & $this->_css;
        $this->data['_js'] = & $this->_js;
        $this->data['_ignore'] = & $this->_ignore;

        $this->set_var('title', 'Chưa đặt tên');
        $this->set_var('items', FALSE);
        $this->set_var('id', FALSE);

        $this->_cookie_login();
        $this->_menu();
    }

    /**
     * Load Proto library
     */
    protected function load_proto_libray(){
    	$this->load->library('pb4php/Pb4php');
    	$this->load->library('proto/proto');
    	$this->load->helper('acx');
    }

    private function _cookie_login()
    {
        if ($this->owner_id) return;

        $username = get_cookie('login_name');
        $password = get_cookie('login_pass');

        if (!$username OR !$password) return;

        $this->load->model('m_user');
        $user = $this->m_user->select_one(array('u_name' => $username));

        if (!$user OR md5($user['u_pass']) != $password) return;

        $sessdata = array('owner_id' => $user['u_id'], 'u_name' => $username, 'loggedin' => TRUE);
        $this->session->set_userdata($sessdata);
        $this->m_user->update(array('u_id' => $user['u_id']), array('u_last_login' => time()));
    }

    protected function get_backend_session_key($type){
        $this->load->model('m_backend_user');
        if($this->session->userdata('backendSessionKey') == ''){
            $this->m_backend_user->backend_login($type);
        }
        return $this->session->userdata('backendSessionKey');
    }

    protected function get_backend_uid($type){

    	$this->load->model('m_backend_user');
    	if($this->session->userdata('backendUid', $type) == '')
    		$this->m_backend_user->backend_login($type);

    	return $this->session->userdata('backendUid', $type);
    }

    private function _menu()
    {
        $this->load->config('menu');
        $menu = $this->config->item('menu');

        $menu_list = array();
        $this->load->model('m_user');
        $this->load->model('m_user_has_group');
        $user = $this->m_user->select_one(array('u_id' => intval($this->owner_id)));

        $user_roles = $this->m_user_has_group->multi_select_user_roles(array('user_id' => $this->owner_id));

        $owner_role = array(); // Mảng chứa vai trò của người truy cập
        $total_role = array(); // Mảng chứa toàn bộ vai trò mà hệ thống giới hạn trong Menu Config
        if ($user)
        {
        	if($user_roles){
				// unserialize all the role and merge them the $role array
        		foreach ($user_roles as $user_role){
        			if(!isset($role))
		            $role = unserialize($user_role['ug_role']);
        			else
        				$role = array_merge($role, unserialize($user_role['ug_role']));
        		}

	            foreach ($menu as $cls => $data)
	            {
	                $data2 = $data;
	                unset($data2['method']);
	                $menu_list[$cls] = $data2;
	                $show_menu = 0;
	                foreach ($data['method'] as $func => $f_data)
	                {
	                    // Vai trò được được lấy từ Config Menu
	                    $total_role[] = "$cls:$func";
	                    if (in_array("$cls:$func", $role))
	                    {
	                        // Nếu tồn tại 1 phần tử của menu hiển thị
	                        if ($f_data['display'] == 1) $show_menu = 1;
	                        $func = str_replace('(:owner_id)', $this->owner_id, $func);
	                        $owner_role[] = "$cls:$func";
	                        $menu_list[$cls]['method'][$func] = $f_data;
	                    }
	                }
	                // Menu bị ẩn đi nếu không có phần tử con nào hiển thị
                	$menu_list[$cls]['display'] = $show_menu;

	            }

        	}
        }

        $this->set_var('menu_list', $menu_list);

        $s1 = $this->uri->segment(1);
        $s2 = $this->uri->segment(2);
        $s3 = $this->uri->segment(3);

        if (isset($user['u_status']))
                if ($user['u_status'] != 1)
                    if ($s1 != 'user' OR $s2 != 'logout')
                        redirect('user/logout');

        // Nếu chưa đăng nhập
        if (!$this->owner_id)
        // Mà không phải đang ở trang Login
                if ($s1 != 'user' OR $s2 != 'login')
                    redirect('user/login'); // Thì chuyển về trang login

            /**
             * Chỉ kiểm tra quyền cho các tính năng có nằm trong Config Menu
             * nếu tính năng không nằm trong giới hạn này, thì cho phép truy cập
             * VD: tính năng user/login thì ai cũng được truy cập
             */
        if (in_array("$s1:$s2", $total_role))
        {
            // Nếu tính năng đang truy cập không nằm trong danh sách vai trò được phân
            // cho người truy cập này thì báo không tìm thấy
            if (!in_array("$s1:$s2", $owner_role) && !in_array("$s1:$s2/$s3", $owner_role))
                    redirect(404);
        }
    }

    protected function set_var($var, $value)
    {
        $this->data[$var] = $value;
    }

    protected function get_var($var)
    {
        return isset($this->data[$var]) ? $this->data[$var] : FALSE;
    }

    protected function view($view, $ajax = FALSE, $return = FALSE)
    {
        if (!$ajax)
        {
            $this->set_var('tpl_header', $this->_header());
            $this->set_var('tpl_left', $this->_left());
//            $this->set_var('tpl_right', $this->_right());
            $this->set_var('tpl_footer', $this->_footer());
        }

        $this->set_var('tpl_content', $this->load_view($view, $this->data, TRUE));

        return $this->load_view($this->template, $this->data, $return);
    }

    protected function load_view($view_file, $data = array(), $return = TRUE)
    {
        $view_path = APPPATH . 'views/';
        $view_ext = pathinfo($view_file, PATHINFO_EXTENSION);
        $view_file = ($view_ext == '') ? $view_file . '.php' : $view_file;

        $file = 'default/' . $view_file;
        if (file_exists($view_path . $this->theme . '/' . $view_file))
                $file = $this->theme . '/' . $view_file;
        
        if (ENABLE_PARSER)
        {
            $this->load->library('parser');
            $views = $this->parser->parse($file, $data, $return);
        }
        else $views = $this->load->view($file, $data, $return);
        
        return $views;
    }

    protected function _header()
    {
        return $this->load_view('header', $this->data);
    }

    protected function _footer()
    {
        if (!$foot = $this->cache->get('foot'))
        {
            $foot = $this->load_view('footer');
            $this->cache->file->save('foot', $foot, CACHE_ELEMENT);
        }

        return $foot;
    }

    protected function _left()
    {
        $v_data['left_widget'] = "";
        if (is_array($this->left_items) && count($this->left_items) > 0)
        {
            $this->load->library('widget');
            $this->widget->set_theme($this->theme);

            foreach ($this->left_items as $widget)
            {
                $v_data['left_widget'] .= $this->widget->get($widget);
            }
        }
        return $this->load_view('left', $v_data);
    }

    protected function _right()
    {
        if (!$right = $this->cache->get('right'))
        {
            $v_data['right_widget'] = "";
            if (is_array($this->right_items) && count($this->right_items) > 0)
            {
                $this->load->library('widget');
                $this->widget->set_theme($this->theme);
                foreach ($this->right_items as $widget)
                {
                    $v_data['right_widget'] .= $this->widget->get($widget);
                }
            }

            $right = $this->load_view('right', $v_data);
            $this->cache->file->save('right', $right, CACHE_ELEMENT);
        }

        return $right;
    }

    protected function solr_update($id, $data = array())
    {
        if (SERVER == 'local') return;

        if (!is_array($data)) return;

        if (empty($data)) return;

        $doc = new KoSolr_Document();
        $doc->id = $id;
        foreach ($data as $key => $value) $doc->$key = $value;
        $update_request = $this->kosolr_server_instance->create_update_request();
        $update_request->add_document($doc);
        $this->kosolr_server_instance->execute($update_request);
    }

    protected function solr_del($id)
    {
        if (SERVER == 'local') return;

        $this->kosolr_server_instance->execute($this->kosolr_server_instance->create_delete_request("id:$id"));
    }

    /**
     * Xử lý và lưu lại ảnh up lên
     * @param array $photo_arr mảng các ảnh
     * @param bool $thumb TRUE nếu là ảnh thumbnail
     * @return string chuỗi ảnh để lưu vào csdl
     */
    protected function _save_photo($photo_arr, $thumb = FALSE, $photo_dir = PHOTO_DIR)
    {
        if (empty($photo_arr)) return;

        $photo_result = array();
        foreach ($photo_arr as $file)
        {
            if (trim($file) == '') continue;

            $time = time();
            $sav_dir = '/' . date('Y/md', $time);
            $today_dir = $photo_dir . $sav_dir;

            if (!is_dir($today_dir)) mkdir($today_dir, 0777, TRUE);

            $new_path = '';
            if (file_exists($file))
            {
                if (!file_exists($today_dir . '/' . $time . '_' . basename($file)))
                        rename($file, $today_dir . '/' . $time . '_' . basename($file));

                $new_path = $sav_dir . '/' . $time . '_' . basename($file);
            }

            if ($new_path == '') continue;

            $photo_result[] = nice_url($new_path);

            if ($thumb)
            {
                $this->load->library('image_lib');

                $img_conf = array();
                $img_conf['image_library'] = 'gd2';
                $img_conf['source_image'] = $photo_dir . $new_path;
                $img_conf['create_thumb'] = FALSE;
                $img_conf['maintain_ratio'] = FALSE;

                $l_conf = $img_conf;
                $l_conf['width'] = THUMB_L_W;
                $l_conf['height'] = THUMB_L_H;
                $l_conf['new_image'] = $today_dir . '/l_' . basename($new_path);
                $this->image_lib->initialize($l_conf);
                $this->image_lib->resize();

                $m_conf = $img_conf;
                $m_conf['width'] = THUMB_M_W;
                $m_conf['height'] = THUMB_M_H;
                $m_conf['new_image'] = $today_dir . '/m_' . basename($new_path);
                $this->image_lib->initialize($m_conf);
                $this->image_lib->resize();

                $s_conf = $img_conf;
                $s_conf['width'] = THUMB_S_W;
                $s_conf['height'] = THUMB_S_H;
                $s_conf['new_image'] = $today_dir . '/s_' . basename($new_path);
                $this->image_lib->initialize($s_conf);
                $this->image_lib->resize();
            }
        }

        if (!empty($photo_result)) return implode(",", $photo_result);
        else return "";
    }

    protected function graph_update($data)
    {
        if (SERVER == 'local') return;
        $respone = $this->__getContent(GRAPHDB_API, $data, "POST", TRUE);
        $status = json_decode($respone);
//        if (@$status->status->code != 1500)
//        {
        $log = date("d/m/Y H:i:s", time())
            . " - Code: " . @$status->status->code
            . " - Desc: " . @$status->status->desc
            . " - Data: " . json_encode($data);
        $this->log($log, "graph");
//        }
    }

    /**
     * Hàm gọi API
     * @param string $url
     * @param null $data
     * @param string $method
     * @param boolean $use_curl
     * @return mix
     */
    protected function __getContent($url, $data = null, $method = "GET", $use_curl = false)
    {
        if (!is_array($data)) $data = null;
        if (count($data) > 0)
        {
            $postdata = urldecode(http_build_query($data, '', '&'));
        }
        else $postdata = "";
        if ($method != "POST") $method = "GET";

        if ($use_curl === true)
        {
            $ch = curl_init();
            //FIXME: parameterize header and useragent
            $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
            $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
            $header[] = "Cache-Control: max-age=0";
            $header[] = "Connection: keep-alive";
            $header[] = "Keep-Alive: 300";
            $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
            $header[] = "Accept-Language: en-us,en;q=0.5";
            $header[] = "Pragma: "; // browsers keep this blank.
            curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.49 Safari/537.1");
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

            if ($method == "POST")
            {
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
            }
            else
            {
                curl_setopt($ch, CURLOPT_URL, $url . "?" . $postdata);
            }
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            $content = curl_exec($ch);
            curl_close($ch);
        }
        else
        {
            $opts = array(
                'http' => array(
                    'method' => $method,
                    'content' => $postdata
                )
            );
            $context = stream_context_create($opts);

            if ($method == "GET")
            {
                if (isset($postdata)) $url = $url . "?" . $postdata;
                $content = @file_get_contents($url);
            } else
            {
                $content = @file_get_contents($url, false, $context);
            }
        }
        return $content;
    }

    protected function log($data, $filename = "log")
    {
        $dir = "./logs/" . date("Ym");
        @mkdir($dir, 0777, TRUE);

        $filename = date("d") . "_$filename";
        $data .= "\n";

        @file_put_contents("$dir/$filename", $data, FILE_APPEND | LOCK_EX);
    }

    /**
     * Hàm lấy EID
     * @return string eid
     */
    protected function __getEid()
    {
        try
        {
            $respone = $this->__getContent(CREATE_EID_API);
            if (!$respone) return '';
            $result = @json_decode($respone);
            return @$result->params->alphaId;
        }
        catch (Exception $exc)
        {
            $this->log($exc->getTraceAsString());
        }
    }

    /**
     * Save media file
     *
     * @param string $file_path
     * @return boolean
     */
    protected function __save_media_file($file_path, $sessionkey, $uid, $file_status="ACTIVE"){
    	try{
//                $fp = fopen("/tmp/loog", "w");
	    	$ch = curl_init();
	    	curl_setopt($ch, CURLOPT_HEADER, 0);
	    	curl_setopt($ch, CURLOPT_VERBOSE, FALSE);
//                curl_setopt($ch, CURLOPT_STDERR, $fp);
	    	curl_setopt($ch, CURLOPT_TIMEOUT, 30);
	    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	    	curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
	    	curl_setopt($ch, CURLOPT_URL, $this->media_server['post_url']['upload']);
	    	curl_setopt($ch, CURLOPT_POST, true);
	    	$mime_type =  mime_content_type($file_path);

	    	$post = array(
	    		"file"=>"@" . $file_path .  ';type='. $mime_type ,
	    		"status" => $file_status,
                        "sessionkey" => $sessionkey,
                        "uid" => $uid,
	    	);               

	    	list($type, $extension) = explode("/", $mime_type);
	    	$uploadType = 'content_picture';
	    	switch($type){
	    		case 'image':
	    			$uploadType = 'content_picture';
	    			break;
	    		default:
	    			$uploadType = 'content_picture';
	    			break;
	    	}

	    	$post['uploadType'] = $uploadType;
	    	curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
	    	$response = curl_exec($ch);
                
	    	$jsonResponse = json_decode($response);
                
	    	if($jsonResponse == NULL || $jsonResponse == false ||  $jsonResponse->{"error_code"} != 0){
                        log_message("error","Error while storing file to media server. \n" . curl_error($ch));
                        curl_close($ch);
	    		return NULL;
	    	}else{

	    		$this->log("Successfully store file($file_path) to media server, object_id(" . $jsonResponse->{"object_id"} . ") \n");
                        curl_close($ch);
	    		return $jsonResponse->{"object_id"};
	    	}
    	}catch(Exception $e){
                $this->log($e->getTraceAsString());
    		$this->log("Exception while storing file to media server: \n" . $e->getMessage());
    		return NULL;
    	}
    }

    /**
     * __update_media_file file
     *
     * Update media file
     * @param string $file_id
     * @param string $file_status
     * @return boolean
     */
    protected function __update_media_file($file_id, $file_status="ACTIVE"){
    	try{
    		$ch = curl_init();
    		curl_setopt($ch, CURLOPT_HEADER, 0);
    		curl_setopt($ch, CURLOPT_VERBOSE, 0);
    		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    		curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
    		curl_setopt($ch, CURLOPT_URL, $this->media_server['post_url']['update']);
    		curl_setopt($ch, CURLOPT_POST, true);
    		$post = array(
    				"id"=> $file_id ,
    				"status" => $file_status,
    		);
    		$uploadType = 'content_picture';
    		$post['uploadType'] = $uploadType;
    		curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    		$response = curl_exec($ch);
    		curl_close($ch);
    		$jsonResponse = json_decode($response);
    		if($jsonResponse->{"error_code"} != 0){
    			$this->log("Error while storing file to media server: \n" . $jsonResponse->{"error_message"});
    			return FALSE;
    		}else{
    			$this->log("Successfully update media server, object_id(" . $file_id . ") \n");
    			return TRUE;
    		}
    	}catch(Exception $e){
    		$this->log("Exception while storing file to media server: \n" . $e->getMessage());
    		return FALSE;
    	}
    }

    protected function __get_media_url($media_uri){
    	list($object_id, $media_id) = explode("@", $media_uri);
    	return $this->media_server['get_url'][$media_id] . $object_id;
    }

    protected function __get_media_id($media_uri){
    	list($object_id, $media_id) = explode("@", $media_uri);
    	return $object_id;
    }

}

/**
 * End file MY_Controller.php
 */
